import { useEffect, useState } from 'react';
import './index.scss';
import { useNavigate } from 'react-router-dom';
import useFetch from '../../../hooks/useFetch';
import { useAppSelector } from '../../../store/hook';
import LazyLoadImg from '../../../components/LazyLoadImg';
import ContentWrapper from '../../../components/ContentWrapper';

const HeroBanner: React.FC = () => {
  const [background, setBackground] = useState('');
  const [query, setQuery] = useState('');
  const navigate = useNavigate();
  const { url } = useAppSelector(state => state.home);

  const { data, loading } = useFetch('/movie/upcoming');

  useEffect(() => {
    const bg = url.backdrop + data?.results?.[Math.floor(Math.random() * 20)]?.backdrop_path;
    setBackground(bg);
  }, [data]);

  const searchQueryHandler = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter' && query.length > 0) {
      navigate(`/search/${query}`);
    }
  };

  return (
    <div className="hero-banner">
      {!loading && (
        <div className="backdrop-img">
          <LazyLoadImg src={background}></LazyLoadImg>
        </div>
      )}

      <div className="opacity-layer"></div>

      <ContentWrapper>
        <div className="hero-banner-content">
          <span className="title">欢迎。</span>
          <span className="sub-title">这里有海量的电影、剧集和人物等你来发现。快来探索吧！</span>
          <div className="search-input">
            <input
              type="text"
              placeholder="搜索电影、剧情、人物..."
              onKeyUp={e => searchQueryHandler(e)}
              onChange={e => setQuery(e.target.value.trim())}
            />
            <button>搜索</button>
          </div>
        </div>
      </ContentWrapper>
    </div>
  );
};

export default HeroBanner;
